package com.qf.wemedia.controller;


import com.qf.common.orderstate.OrderState;
import com.qf.common.response.Response;
import com.qf.common.wxpay.MyWXConfig;
import com.qf.common.wxpay.WXPay;
import com.qf.entity.dto.Goods;
import com.qf.entity.dto.Orders;
import com.qf.entity.po.LoginMerchant;
import com.qf.service.GoodsService;
import com.qf.service.GoodsSkuService;
import com.qf.service.OrdersService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
@RequestMapping("order")
public class OrderController {
    @Resource
    GoodsService goodsService;
    @Resource
    OrdersService ordersService;
    @Resource
    GoodsSkuService goodsSkuService;

    /**
     * 前往创建订单页面，携带数据
     * 商品信息goods  购买人数buyerNumber  套餐信息skuList
     */
    @RequestMapping("new")
    public String toGoodsList(Model model, @RequestParam(value = "goodsId", required = true) Long goodsId) {
        model.addAttribute("goods", goodsService.getById(goodsId));
        model.addAttribute("buyerNumber", ordersService.getBuyerNumberByGoodsId(goodsId));
        model.addAttribute("skuList", goodsSkuService.getSkuListByGoodsId(goodsId));
        return "order/new";
    }

    /**
     * 根据订单信息创建订单
     */
    @RequestMapping("createOrder")
    @ResponseBody
    public Response<?> createOrder(Orders orders, LoginMerchant loginMerchant) {
        ordersService.createOrder(orders, loginMerchant);
        return Response.success();
    }

    /**
     * 前往该商户处理的订单清单页面
     *
     * @param loginMerchant
     * @return
     */
    @RequestMapping("list")
    public String toOrderList(Model model, LoginMerchant loginMerchant) {
        model.addAttribute("orderList", ordersService.getOrderListByMerchantId(loginMerchant.getId()));
        return "order/list";
    }

    /**
     * 前往支付页面，目前支持微信支付
     *
     * @param orderId
     * @return
     */
    @RequestMapping("wxpay")
    public String toWeiXinPay(Model model, @RequestParam(value = "orderId", required = true) Long orderId) {
        model.addAttribute("order", ordersService.getById(orderId));
        return "order/wxpay";
    }

    /**
     * 获取价格的二维码图片，通过微信接口获取
     *
     * @param orderId
     * @return
     */
    @RequestMapping("getQR")
    @ResponseBody
    public Response<?> getQR(@RequestParam(value = "orderId") Long orderId, LoginMerchant loginMerchant) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        try {
            Orders order = ordersService.getById(orderId);
            WXPay wxPay = new WXPay(new MyWXConfig());
            Long goodsId = order.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            Map<String, String> data = new LinkedHashMap<>();
            data.put("body", goods.getName());  //商品描述
            data.put("out_trade_no", sdf.format(new Date()).concat(loginMerchant.getId().toString()).concat(String.valueOf(RandomUtils.nextInt(10000, 100000)))); //外部订单号
            data.put("fee_type", "CNY"); //币种
            data.put("total_fee", order.getPrice().toString()); //金额，单位:分 !
            data.put("spbill_create_ip", "127.0.0.1"); //终端ip
            data.put("notify_url", "http://m7t3qb.natappfree.cc/callback/wxpay/notifyCall"); //回调地址
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", goodsId.toString()); //商品id
            data.put("attach", order.getNumber()); //内部订单号
            try {
                Map<String, String> resp = wxPay.unifiedOrder(data);
                String resultCode = resp.get("result_code");
                if ("FAIL".equals(resultCode)) {
                    return Response.fail(resp.get("err_code_des"));
                } else {
                    return Response.success(resp.get("code_url"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.fail("支付失败");
    }

    /**
     * 支付成功后跳转的页面，获取该订单的支付状态，如果是已支付，就刷新页面
     *
     * @param orderId
     * @return
     */
    @RequestMapping("getPayStatus")
    @ResponseBody
    public Response<?> getPayStatus(@RequestParam(value = "orderId") Long orderId) {
        Orders order = ordersService.getById(orderId);
        if (OrderState.ALREADY_PAID.getCode().equals(order.getPayStatus())) {
            return Response.success("PAID");
        } else {
            return Response.success("UNPAID");
        }
    }
}
